#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2020/10/11 10:22
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：连接池

import os
from contextlib import contextmanager

import cx_Oracle
from sql_base import Base

os.environ['NLS_LANG'] = 'AMERICAN_AMERICA.ZHS16GBK'


class Pool(Base):
    """docstring for Pool"""

    def __init__(self, **kwargs):
        super(Pool, self).__init__()
        self.__dict__ = kwargs
        self.pool = self._getConnectPool()

    # 默认没有的属性为None
    def __getattr__(self, key):
        return 0

    # 初始连接池
    def _getConnectPool(self):
        dsn = "{}:{}/{}".format(self.host, self.port or 1521, self.database)
        min = int(self.mincached or 5)
        max = int(self.mincached or 5)
        pool = cx_Oracle.SessionPool(self.username, self.password, dsn, min = min, max = max, increment = 0,
                                     threaded = True)
        return pool
    # 获取连接游标
    @contextmanager
    def getCursor(self):
        try:
            con = self.pool.acquire()
            cursor = con.cursor()
            yield cursor
        finally:
            cursor.close()
            con.close()


if __name__ == '__main__':
    import time_ext_
    from concurrent.futures import ThreadPoolExecutor
    import loadConfig

    ini = loadConfig.loadIni("./config/config.ini")()
    config = ini.get("Oracle1")
    print(config)

    pool = Pool(**config)


    def t(n):
        r = pool.loadSql("SELECT SYSDATE XX FROM  DUAL")
        print('线程:{},值:{}\n'.format(n, r))

    s = time_ext_.time()
    with ThreadPoolExecutor(max_workers = 5) as aa:
        for i in range(5):
            aa.submit(t, (i))

    print(time_ext_.time() - s)